package org.light.framework.util;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.imageio.ImageIO;

public class DrawUtil {

    /**
     * 生成图片
     * 
     * @param filePath
     * @param imageWith
     * @param lineHeight
     * @param font
     * @param drawItems
     * @throws IOException
     */
    public static byte[] drawImage(int imageWith, List<DrawItem> drawItems) throws IOException {

        if (drawItems == null || drawItems.size() == 0) {
            System.out.println("没有要绘制的项");
            return null;
        }

        int imageHeight = getImageHeight(drawItems);

        BufferedImage bi = new BufferedImage(imageWith, imageHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = (Graphics2D) bi.getGraphics();
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setBackground(Color.WHITE);
        g2.clearRect(0, 0, imageWith, imageHeight);

        for (DrawItem di : drawItems) {
            if (di.getType() == DrawItemTypeEnum.IMAGE) {

                File bgImageFile = new File(di.getContent());
                if (!bgImageFile.exists()) {
                    System.out.println("图片不存在");
                    continue;
                } else {
                    Image img = ImageIO.read(bgImageFile);
                    g2.drawImage(img.getScaledInstance(img.getWidth(null), img.getHeight(null), Image.SCALE_SMOOTH), 0, di.getStartY(), null);
                }

            } else if (di.getType() == DrawItemTypeEnum.TEXT) {

                int x = di.getStartX();

                // 文字居中
                if (di.isCenter()) {

                    FontRenderContext context = g2.getFontRenderContext();
                    Rectangle2D bounds = di.getFont().getStringBounds(di.getContent(), context);
                    x = (int) ((imageWith - bounds.getWidth()) / 2);
                }

                g2.setFont(di.getFont());
                g2.setPaint(di.getColor());
                g2.drawString(di.getContent(), x, di.getStartY());
            }
        }

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ImageIO.write(bi, "png", out);
        return out.toByteArray();
    }

    /**
     * 获取高度
     * 
     * @param drawItems
     * @return
     */
    public static int getImageHeight(List<DrawItem> drawItems) {

        int height = 0;
        for (DrawItem drawItem : drawItems) {
            if (drawItem.getType() == DrawItemTypeEnum.IMAGE)
                height += drawItem.getHeight();
        }
        return height;
    }
}
